<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class GoodscategoryController extends Controller
{
    //商品分类列表
    public function goodscategory_list(){
    	$arr=DB::table('goodscategory')->orderByRaw('concat(type,id)')->get();

    	return view('/admin/goodscategory/goodscategory_list',['arr'=>$arr]);
    }
    // 添加
    public function goodscategory_add(){
    	$arr=DB::table('goodscategory')->orderByRaw('concat(type,id)')->get();
    	return view('/admin/goodscategory/goodscategory_add',['arr'=>$arr]);
    }
    //添加至数据库
    public function goodscategory_insert(Request $request){
    	//dd($request->all());
    	if($request->pid==0){
    		$type='0,';
    	}else{
 		   	$type=DB::table('goodscategory')->where('id',$request->pid)->value('type').DB::table('goodscategory')->where('id',$request->pid)->value('id').',';
    	}
        $rank=substr_count($type,',');
    	$n=$request->all();
    	$n['type']=$type;
        $n['rank']=$rank;
    	if(DB::table('goodscategory')->insert($n)){
    		return 1;
    	}else{
    		return 0;
    	}
    	// return redirect()->action('admin\goodscategoryController@goodscategory_list');
    }

    // 从数据库中删除
    public function goodscategory_del(Request $request){
    	// 有子类和商品的分类不能删除
    	$allcls=DB::table('goodscategory')->get();
    	$allgoods=DB::table('goods')->get();
    	foreach($request->ids as $id){
    		// return $id;
    		// 子类判断
    		foreach($allcls as $alld){
    			if($alld->pid==$id){
    				return -1;
    			}
    		}
    		// 商品判断
    		foreach($allgoods as $allg){
    			if($allg->type==$id){
    				return -1;
    			}
    		}
    	}
    	if(DB::table('goodscategory')->whereIn('id',$request->ids)->delete()){
    		return 1;
    	}else{
    		return 0;
    	}
    }

    // 修改数据库内容
    public function goodscategory_update(Request $request){
    	$data=$request->all();
    	$data['classify']=ltrim($data['classify'],'——');
    	$data['classify']=ltrim($data['classify'],' ');
    	// return $data;
		if(DB::table('goodscategory')->where('id',$request->id)->update($data)){
			return 1;
		}else{
			return 0;
		}
	}
}
